import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DragDropService {

  private dragStatus: any;
  /** 判断是否是dom对象 */
  private isDOM = (typeof HTMLElement === 'object') ?
    function (obj) {
      return obj instanceof HTMLElement;
    } :
    function (obj) {
      return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
    };
  constructor() { }

  /**
   * 初始化拖拽
   * @param element 被拖拽的对象
   * @param dragHandle 触发拖拽的对象
   */
  startDragDrop(element, dragHandle?) {
    setTimeout(() => {

      if (!dragHandle) {
        dragHandle = element.querySelector('.ant-modal-header');
      } else if (typeof dragHandle === 'string') {
        dragHandle = element.querySelector(dragHandle);
      } else if (this.isDOM(dragHandle)) {
        // console.log(dragHandle);
      }

      if (!dragHandle) {
        // tslint:disable-next-line:no-console
        console.error('Element not found');
        return;
      }
      // 初始化拖拽状态
      this.dragStatus = { currentX: 0, currentY: 0, moveX: 0, moveY: 0, flag: false };
      // 给模态窗添加样式
      element.style.cssText += 'touch-action: none;-webkit-user-drag: none;-webkit-tap-highlight-color: transparent;user-select: none;';
      // 给模态窗标题添加样式
      dragHandle.style.cssText += 'cursor:move';

      /**
       * 鼠标移动
       *  */
      const onMousemove = (e) => {
        if (this.dragStatus.flag) {
          // 当前移动距离
          const moveX = e.clientX - this.dragStatus.currentX;
          const moveY = e.clientY - this.dragStatus.currentY;

          // 当前移动距离加上历史距离等于实际移动距离
          element.style.transform = `translate(${moveX + this.dragStatus.moveX}px, ${moveY + this.dragStatus.moveY}px)`;
          // console.log(`鼠标移动${JSON.stringify(this.dragStatus)}`);
        }
      };
      /**
       * 鼠标在模态窗标题区域按下
       *  */
      const onMousedown = (e) => {
        this.dragStatus.flag = true;
        this.dragStatus.currentX = e.clientX;
        this.dragStatus.currentY = e.clientY;
        // console.log(`按下${JSON.stringify(this.dragStatus)}`);
        // 防止IE文字选中
        dragHandle.onselectstart = () => false;
        document.addEventListener('mousemove', onMousemove);
      };
      /**
       * 鼠标抬起
       *  */
      const onMouseup = (e) => {
        if (this.dragStatus.flag) {
          // 记录历史移动距离
          this.dragStatus.moveX = e.clientX - this.dragStatus.currentX + this.dragStatus.moveX;
          this.dragStatus.moveY = e.clientY - this.dragStatus.currentY + this.dragStatus.moveY;
          this.dragStatus.flag = false;
          document.removeEventListener('mousemove', onMousemove);
        }
      };

      /** 鼠标在模态窗标题区域按下 */
      dragHandle.addEventListener('mousedown', onMousedown);
      /** 鼠标抬起 */
      dragHandle.addEventListener('mouseup', onMouseup);
      document.addEventListener('mouseup', onMouseup);
    }, 300);
  }
}
